<template>
  <div class="main-container" v-loading="loading">
    <div class="card-container box">
      <div class="left">
        <div class="tab-box">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" tab="分类代码类别">
              <div class="btn-group">
                <div
                  class="btn-group-item singSvg"
                  @click="()=>{serchMenuLeft();$message.success('刷新成功')}"
                >
                  <IconFont type="swx-icon-gengxin" />刷新
                </div>
                <div class="btn-group-item" @click="addfldmlbBtn">
                  <IconFont type="swx-icon-tianjia" />添加
                </div>
                <div class="btn-group-item" @click="onEdit">
                  <IconFont type="swx-icon-bianjiiconkaobei14" />编辑
                </div>
                <div class="btn-group-item btn-group-delete-item" @click="delet">
                  <IconFont type="swx-icon-shanchu" />移除
                </div>
              </div>
              <div class="bottom" style="margin-top:20px;height:calc(100% - 32px)">
                <a-input-search style="margin-bottom: 8px" @change="onChange" allow-clear />
                <a-tree
                  defaultExpandAll
                  show-icon
                  :tree-data="gData"
                  :replace-fields="replaceFields"
                  blockNode
                  @select="treeSelect"
                  :selectedKeys="test"
                >
                  <IconFont type="swx-icon-zhankaiwenjianjiaiconkaobei2" slot="1" />
                  <IconFont type="swx-icon-wenshu-wendang" slot="2" />
                </a-tree>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
      <div class="right">
        <div class="tab-box">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" tab="分类代码">
              <div style="height:40px">
                <div style="float:left">
                  <a-input-search style="width: 200px" @change="onSearch" />
                </div>
                <div style="float:right">
                  <div class="btn-group">
                    <div class="btn-group-item" style="margin-right:10px" @click="add">
                      <IconFont type="swx-icon-tianjia" />添加
                    </div>
                    <div class="btn-group-item" @click="addChildDm">
                      <IconFont type="swx-icon-tianjia" />添加子代码
                    </div>
                  </div>
                </div>
              </div>

              <div style="margin-top:10px;height:calc(100% - 46px)">
                <a-table
                  :columns="columns"
                  :data-source="tableLists"
                  :pagination="false"
                  :row-selection="rowSelection"
                >
                  <template slot="action" slot-scope="text,record">
                    <a slot="action" href="javascript:;" style="margin-right:4px">
                      <span class="empty-btn" @click="bianJi(text)">
                        <IconFont type="swx-icon-bianjiiconkaobei14" />编辑
                      </span>
                    </a>
                    <a slot="action" href="javascript:;">
                      <span class="empty-btn" @click="deletTable(text)">
                        <IconFont type="swx-icon-shanchu" />移除
                      </span>
                    </a>
                  </template>
                </a-table>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
    </div>

    <!-- 添加分类代码类别 -->
    <a-modal
      v-model="addfldmlbDia"
      :title="fldmlbTitle"
      @ok="addfldm"
      class="bydm"
      @cancel="close"
      centered
    >
      <table class="riginalTable" style="table-layout:fixed;">
        <tr>
          <td style="width:35%">
            类别名称
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="addForm.lbmc" />
          </td>
        </tr>
        <tr>
          <td>
            类别编码
            <span class="red">（4位）*</span>
          </td>
          <td>
            <input
              class="riginalInput"
              :style="{'cursor':fldmlbTitle=='修改分类代码类别'?'not-allowed':''}"
              v-model="addForm.lbbm"
              :disabled="fldmlbTitle=='修改分类代码类别'"
            />
          </td>
        </tr>
        <tr>
          <td>
            所属类别
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="addForm.dmsslb" />
          </td>
        </tr>
        <tr>
          <td>类别标准</td>
          <td>
            <input class="riginalInput" v-model="addForm.lbbz" />
          </td>
        </tr>
        <tr>
          <td>类别国标代码</td>
          <td>
            <input class="riginalInput" v-model="addForm.lbgbdm" />
          </td>
        </tr>
      </table>
    </a-modal>

    <!-- 添加分类代码2 -->
    <a-modal
      v-model="visible"
      :title="visibleTitle"
      @ok="addfldmQdan"
      class="bydm"
      @cancel="close2"
      centered
    >
      <table class="riginalTable" style="table-layout:fixed;">
        <tr>
          <td style="width:25%">
            代码
            <span class="red">（13位）*</span>
          </td>
          <td>
            <input class="riginalInput" style="float:left;width:80%" v-model="addfldmDiaForm.dm" />
            <span class="btn-item" style="float:right" @click="yaohaoBtn">要号</span>
          </td>
        </tr>
        <tr>
          <td>
            名称
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="addfldmDiaForm.mc" />
          </td>
        </tr>
        <tr>
          <td>
            类别编码(
            <span class="red">4位</span>)
          </td>
          <td>
            <input
              class="riginalInput"
              v-model="addfldmDiaForm.lbbm"
              disabled
              style="cursor:not-allowed"
            />
          </td>
        </tr>
        <!-- <tr>
          <td>序号</td>
          <td>
            <input class="riginalInput" v-model="addfldmDiaForm.xh" />
          </td>
        </tr>-->
        <tr>
          <td>说明</td>
          <td>
            <a-input v-model="addfldmDiaForm.sm" type="textarea" style="border:none;resize:none;" />
          </td>
        </tr>
      </table>
    </a-modal>

    <!-- 修改分类代码 -->
    <a-modal
      v-model="changefldmlbDia"
      title="修改分类代码"
      @ok="changefldmQdan"
      class="bydm"
      @cancel="close1"
      centered
    >
      <table class="riginalTable" style="table-layout:fixed;">
        <tr>
          <td style="width:25%">
            代码
            <span class="red">（13位）*</span>
          </td>
          <td>
            <input
              class="riginalInput"
              v-model="chanefldmDiaForm.dm"
              disabled
              style="cursor:not-allowed"
            />
          </td>
        </tr>
        <tr>
          <td>
            名称
            <span class="red">*</span>
          </td>
          <td>
            <input class="riginalInput" v-model="chanefldmDiaForm.mc" />
          </td>
        </tr>
        <tr>
          <td>
            类别编码(
            <span class="red">4位</span>)
          </td>
          <td>
            <input
              class="riginalInput"
              v-model="chanefldmDiaForm.lbbm"
              disabled
              style="cursor:not-allowed"
            />
          </td>
        </tr>
        <!-- <tr>
          <td>序号</td>
          <td>
            <input class="riginalInput" v-model="chanefldmDiaForm.xh" />
          </td>
        </tr>-->
        <tr>
          <td>说明</td>
          <td>
            <a-input
              v-model="chanefldmDiaForm.sm"
              type="textarea"
              style="border:none;resize:none;"
            />
          </td>
        </tr>
      </table>
    </a-modal>
  </div>
</template>

<script>
import service from './api/api';
const columns = [
  {
    title: "分类代码名称",
    dataIndex: "mc",
  },
  {
    title: "分类代码",
    dataIndex: "dm",
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
  },
];
export default {
  data() {
    return {
      visible: false,
      visibleTitle: "添加分类代码",
      columns,
      replaceFields: {
        children: "children",
        title: "lbmc",
        key: "lbbm",
      },
      test: [],
      gData: [],
      nodeMessege: "",
      tableNodeMessege: "",
      tableLists: [],
      tableLists1: [],
      addForm: {}, //左边的数据
      addfldmlbDia: false,
      changefldmlbDia: false,
      fldmlbTitle: "添加分类代码类别",
      selectedRows: [], //table选中节点
      addfldmDiaForm: {
        dm: "",
        mc: "",
        lbbm: "",
        xh: "",
        sm: "",
        fdm: "",
      },
      chanefldmDiaForm: {
        dm: "",
        mc: "",
        lbbm: "",
        xh: "",
        sm: "",
        fdm: "",
      },
      flag: false,
      loading: false,
    };
  },
  created() {
    this.serchMenuLeft();
  },
  methods: {
    // 遍历增加字段
    diGui(arr) {
      for (let item of arr) {
        item.slots = {};
        item.slots.icon = item.level + "";
        if (item.children && item.children.length > 0) {
          this.diGui(item.children);
        }
      }
      return arr;
    },
    serchMenuLeft() {
      const _this = this;
      service.bydm.queryLeftMenu({}).then((res) => {
        if (res.code == 0) {
          _this.gData = _this.diGui(res.data);
          this.gData1 = JSON.parse(JSON.stringify(_this.gData)); //用于筛选
          this.test = [res.data[0].lbbm]; //设置默认选中值
          this.nodeMessege = res.data[0]; //节点信息
          this.queryTable(); //查询表格
        }
      });
    },
    // 点击的是第几级
    treeSelect(selectedKeys) {
      if (selectedKeys.length > 0) {
        this.test = selectedKeys; //切换节点
        this.nodeMessege = this.getChidlren(this.gData, selectedKeys[0]);
        // debugger;
        if (this.nodeMessege.level == 1) {
          this.tableLists = [];
          return;
        }
        this.queryTable();
        // this.nodeMessege;
      }
    },
    queryTable() {
      this.loading = true;
      let data = {
        lbbm: this.nodeMessege.lbbm,
      };
      service.bydm.queryTable(data).then((res) => {
        if (res.code == 0) {
          this.tableLists = res && res.data;
          this.tableLists1 = res && res.data; //临时保存一个值用于筛选
          this.loading = false;
        }
      });
    },
    addfldmlbBtn() {
      // if (this.nodeMessege.level == 1) {
      //   this.$message.warning("父节点不能点击");
      //   return;
      // }
      // 左边的
      this.addfldmlbDia = true;
      this.fldmlbTitle = "添加分类代码类别";
      this.addForm = {};
    },
    // 左边的 添加 修改 确定按钮
    async addfldm() {
      if (!(this.addForm.dmsslb && this.addForm.lbbm && this.addForm.lbmc)) {
        this.$message.warning("请完善信息");
        return;
      }

      if (this.addForm.lbbm.length != 4) {
        this.$message.error("类别编码只能是4位数");
        return;
      }

      if (this.fldmlbTitle == "添加分类代码类别") {
        let res = await service.bydm.checkLbbm({
          lbbm: this.addForm.lbbm,
        });

        if (res.code == 0) {
          if (res.data.stats) {
            service.bydm.addFldmlb({ ...this.addForm }).then((res) => {
              // console.log(res);
              if (res.code == 0) {
                this.$message.success("添加成功");
                this.addfldmlbDia = false;
                this.serchMenuLeft();
              }
            });
          } else {
            this.$message.error(res.data.data.msg);
          }
        }
      }

      if (this.fldmlbTitle == "修改分类代码类别") {
        service.bydm.changeSingNode({ ...this.addForm }).then((res) => {
          // console.log(res);
          if (res.code == 0) {
            this.$message.success("修改成功");
            this.addfldmlbDia = false;
            this.serchMenuLeft();
          }
        });
      }
    },

    // 编辑按钮
    onEdit() {
      if (this.nodeMessege.level == 1) {
        this.$message.warning("父节点不能点击编辑");
        return;
      }
      this.fldmlbTitle = "修改分类代码类别";
      this.addfldmlbDia = true;
      service.bydm
        .serchSingNode({ lbbm: this.nodeMessege.lbbm })
        .then((res) => {
          if (res.code == 0) {
            this.addForm = res && res.data;
          }
        });
    },

    // 删除按钮
    delet() {
      if (this.nodeMessege.level == 1) {
        this.$message.warning("父分类不能点击删除");
        return;
      }
      service.bydm
        .deletFldmlb({ lbbm: this.nodeMessege.lbbm })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success("删除成功");
            this.serchMenuLeft();
          }
        });
    },
    getChidlren(data1, key) {
      var hasFound = false, // 表示是否有找到id值
        result = null;
      var fn = function (data) {
        if (Array.isArray(data) && !hasFound) {
          // 判断是否是数组并且没有的情况下，
          data.forEach((item) => {
            if (item.lbbm === key) {
              // 数据循环每个子项，并且判断子项下边是否有id值
              result = item; // 返回的结果等于每一项
              hasFound = true; // 并且找到id值
            } else if (item.children) {
              fn(item.children); // 递归调用下边的子项
            }
          });
        }
      };
      fn(data1); // 调用一下
      return result;
    },
    getChidlren1(data1, key) {
      var hasFound = false, // 表示是否有找到id值
        result = null;
      var fn = function (data) {
        if (Array.isArray(data) && !hasFound) {
          // 判断是否是数组并且没有的情况下，
          data.forEach((item) => {
            if (item.key === key) {
              // 数据循环每个子项，并且判断子项下边是否有id值
              result = item; // 返回的结果等于每一项
              hasFound = true; // 并且找到id值
            } else if (item.children) {
              fn(item.children); // 递归调用下边的子项
            }
          });
        }
      };
      fn(data1); // 调用一下
      return result;
    },
    //右边的上的添加按钮
    add() {
      if (this.nodeMessege.level == 1) {
        this.$message.warning("父节点不能点击编辑");
        return;
      }
      this.visibleTitle = "添加分类代码";
      this.visible = true;
      this.addfldmDiaForm.lbbm = this.nodeMessege.lbbm;
    },
    // 添加子代码
    addChildDm() {
      if (this.selectedRows.length <= 0) {
        this.$message.warning("请选择需要添加到的分类");
        return;
      }
      if (this.selectedRows.length > 1) {
        this.$message.warning("只能选择一项分类");
        return;
      }
      this.visibleTitle = "添加分类代码";
      this.flag = true;
      this.visible = true;
      this.addfldmDiaForm.lbbm = this.nodeMessege.lbbm;
    },
    // 摇号
    yaohaoBtn() {
      // if (this.visibleTitle == "修改分类代码") {
      //   return;
      // }

      service.bydm.yaohao({ lbbm: this.nodeMessege.lbbm }).then((res) => {
        if (res.code == 0) {
          this.addfldmDiaForm.dm = res.data.dm;
        }
      });
    },
    // 添加按钮确定弹框
    addfldmQdan() {
      if (!(this.addfldmDiaForm.dm && this.addfldmDiaForm.mc)) {
        this.$message.warning("请完善信息");
        return;
      }

      if (!(this.addfldmDiaForm.dm.length == 13)) {
        this.$message.warning("代码只能输入13位");
        return;
      }
      // flag 为true 为添加子代码
      // flag false  为添加代码
      if (this.flag) {
        this.addfldmDiaForm.fdm = this.tableNodeMessege.dm;
      }

      service.bydm.addDiaApi({ ...this.addfldmDiaForm }).then((res) => {
        if (res.code == 0) {
          this.$message.success("操作成功");
          this.queryTable();
          this.visible = false;
          this.addfldmDiaForm = {
            dm: "",
            mc: "",
            lbbm: "",
            xh: "",
            sm: "",
            fdm: "",
          };
        }
      });
    },
    // 关闭
    close() {
      this.flag = false;
      this.addForm = {};
    },
    close1() {
      this.chanefldmDiaForm = {
        dm: "",
        mc: "",
        lbbm: "",
        xh: "",
        sm: "",
        fdm: "",
      };
    },
    close2() {
      this.addfldmDiaForm = {
        dm: "",
        mc: "",
        lbbm: "",
        xh: "",
        sm: "",
        fdm: "",
      };
    },
    onSearch(e) {
      const value = e.target.value;
      if (value) {
        const tree = JSON.parse(JSON.stringify(this.tableLists1));
        this.tableLists = this.filter1(tree, value);
      } else {
        this.tableLists = this.tableLists1;
      }
    },
    onChange(e) {
      const value = e.target.value;
      if (value) {
        const tree = JSON.parse(JSON.stringify(this.gData1));
        this.gData = this.filter(tree, value);
      } else {
        this.gData = this.gData1;
      }
    },
    // nodes就是树形的最原始数据，query就是关键字，最后会返回满足条件的节点数组
    filter(nodes, query) {
      // 条件就是节点的title过滤关键字
      let predicate = function (node) {
        if (node.lbmc.indexOf(query) > -1) {
          return true;
        } else {
          return false;
        }
      };
      if (!(nodes && nodes.length)) {
        return [];
      }
      let newChildren = [];
      for (let node of nodes) {
        // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
        // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
        // 2. 自己本身符合条件
        let subs = this.filter(node.children, query);
        if (predicate(node)) {
          newChildren.push(node);
        } else if (subs && subs.length) {
          node.children = subs;
          newChildren.push(node);
        }

        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        // if (predicate(node)) {
        //     newChildren.push(node);
        //     node.children = this.filter(node.children, query);
        // } else {
        //     newChildren.push(...this.filter(node.children, query));
        // }
      }
      return newChildren.length ? newChildren : [];
    },
    // nodes就是树形的最原始数据，query就是关键字，最后会返回满足条件的节点数组
    filter1(nodes, query) {
      // 条件就是节点的title过滤关键字
      let predicate = function (node) {
        if (node.mc.indexOf(query) > -1) {
          return true;
        } else {
          return false;
        }
      };
      if (!(nodes && nodes.length)) {
        return [];
      }
      let newChildren = [];
      for (let node of nodes) {
        // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
        // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
        // 2. 自己本身符合条件
        let subs = this.filter(node.children, query);
        if (predicate(node)) {
          newChildren.push(node);
        } else if (subs && subs.length) {
          node.children = subs;
          newChildren.push(node);
        }

        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        // if (predicate(node)) {
        //     newChildren.push(node);
        //     node.children = this.filter(node.children, query);
        // } else {
        //     newChildren.push(...this.filter(node.children, query));
        // }
      }
      return newChildren.length ? newChildren : [];
    },
    bianJi(item) {
      service.bydm.getFldm({ dm: item.dm }).then((res) => {
        console.log(res);
        if (res.code == 0) {
          this.chanefldmDiaForm = res.data;
        }
      });
      // this.chanefldmDiaForm = { ...item };
      // this.chanefldmDiaForm.lbbm = this.nodeMessege.lbbm;
      this.changefldmlbDia = true;
    },
    deletTable(item) {
      service.bydm
        .deletDiaApi({
          dm: item.dm,
        })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success("删除成功");
            this.queryTable();
          }
        });
    },
    changefldmQdan() {
      let data = {
        dm: this.chanefldmDiaForm.dm,
        fdm: this.chanefldmDiaForm.fjdm,
        lbbm: this.chanefldmDiaForm.lbbm,
        mc: this.chanefldmDiaForm.mc,
        sm: this.chanefldmDiaForm.sm,
      };
      service.bydm.changeDiaApi(data).then((res) => {
        if (res.code == 0) {
          this.$message.success("操作成功");
          this.changefldmlbDia = false;
          this.chanefldmDiaForm = {
            dm: "",
            mc: "",
            lbbm: "",
            xh: "",
            sm: "",
            fdm: "",
          };
          this.queryTable();
        }
      });
    },
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.tableNodeMessege = this.getChidlren1(
            this.tableLists,
            selectedRowKeys[0]
          );
          this.selectedRows = selectedRows;
        },
      };
    },
  },
};
</script>

<style lang='less' scoped>
.main-container {
  width: 100%;
  height: 100%;
  .card-container {
    border: 0 !important;
  }
  .left {
    float: left;
    width: 315px;
    height: 100%;
    background-color: #fff;
    border-radius: 5px;
    .tab-box {
      border-radius: 5px;
    }
  }
  .right {
    float: right;
    height: 100%;
    width: calc(100% - 325px);
    background-color: #fff;
    border-radius: 5px;
    .tab-box {
      border-radius: 5px;
    }
  }
}
/deep/ .ant-tabs-bar {
  margin: 0;
}
/deep/ .ant-tabs-nav-container {
  height: 40px;
}
/deep/ .ant-tabs-nav-wrap,
/deep/ .ant-tabs-nav-scroll,
/deep/ .ant-tabs-nav,
/deep/ .ant-tabs-tab {
  height: 40px;
}
/deep/ .ant-tabs-tabpane {
  padding: 16px;
}
/deep/ .ant-tabs {
  height: 100%;
}
/deep/ .ant-tabs-content {
  height: calc(100% - 40px);
}
/deep/ .ant-tabs-tabpane {
  height: 100%;
}
/deep/ .tab-box,
/deep/ .ant-tabs {
  height: 100%;
}

/deep/ .ant-input:focus {
  box-shadow: none;
}
.bydm /deep/ .ant-modal {
  min-width: 700px !important;
}
/deep/ .ant-tabs-content {
  height: calc(100% - 44px);
}
/deep/ .ant-table-wrapper {
  height: 100%;
  .ant-spin-nested-loading {
    height: 100%;
    .ant-spin-container {
      height: 100%;
      .ant-table {
        height: 100%;
        overflow: auto;
      }
    }
  }
}
/deep/ .ant-table-body {
  border: none !important;
}
/deep/ .ant-tree {
  height: calc(100% - 42px);
}

/deep/ .box > .ant-tabs > .ant-tabs-content {
  height: calc(100% - 37px) !important;
}
/deep/ .ant-tree-node-content-wrapper {
  padding-left: 6px !important;
}
.bottom .ant-tree {
  height: calc(100% - 50px);
  overflow: auto;
}
</style>
